﻿CREATE PROCEDURE [ServiceEngine].[CreateSchemaObjectDependency]
@SchemaObjectID UNIQUEIDENTIFIER, 
@ParentObjectID UNIQUEIDENTIFIER, 
@ImportNamespace NVARCHAR (256),
@ID UNIQUEIDENTIFIER OUTPUT
AS
BEGIN
	DECLARE @ErrorMessage NVARCHAR(4000);
	DECLARE @ErrorSeverity INT;
	DECLARE @ErrorState INT;
	
	DECLARE @ParentSchemaID UNIQUEIDENTIFIER;
	DECLARE @ImportID UNIQUEIDENTIFIER;
	
	SET NOCOUNT ON;
	BEGIN TRY
		SELECT @ID = [SchemaObjectDependencyID] FROM [ServiceEngine].[SchemaObjectDependencies] WHERE [SchemaObjectID] = @SchemaObjectID AND [ParentObjectID] = @ParentObjectID
		IF @ID IS NULL
		BEGIN
			SET @ID = NewID()
			INSERT INTO [ServiceEngine].[SchemaObjectDependencies]
				   ([SchemaObjectDependencyID]
				   ,[SchemaObjectID]
				   ,[ParentObjectID])
			 VALUES
				   (@ID
				   ,@SchemaObjectID
				   ,@ParentObjectID)
				   
			SELECT @ParentSchemaID = SO.SchemaID FROM [ServiceEngine].[SchemaObjects] SO WHERE SO.SchemaObjectID = @ParentObjectID
			-- Set the import schema also
			EXEC [ServiceEngine].[CreateSchemaImport] @ParentSchemaID,@ImportNamespace,  @ImportID OUT
		END
	END TRY
	BEGIN CATCH
		SELECT 
			@ErrorMessage = ERROR_MESSAGE(),
			@ErrorSeverity = ERROR_SEVERITY(),
			@ErrorState = ERROR_STATE();

		IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;

		RAISERROR (@ErrorMessage, 
				   @ErrorSeverity,
				   1);
	END CATCH
END

